export default class Ws extends WebSocket {
    wsUrl: string;
    heartbeatTimer: NodeJS.Timeout | null;
    reconnectingTimer: NodeJS.Timeout | null;
    wsReconnect: Function;
    constructor(url: string, wsReconnect: Function) {
        super(url);
        this.wsUrl = url;
        this.heartbeatTimer = null;
        this.reconnectingTimer = null;
        this.wsReconnect = wsReconnect;
        this.init();
    }

    init() {
        console.log("初始化");

        this.bindEvent();
    }

    bindEvent() {
        this.addEventListener("open", this.handleOpen, false);
        this.addEventListener("close", this.handleClose, false);
        this.addEventListener("error", this.handleError, false);
        this.addEventListener("message", handleMessage, false);
    }
    handleOpen(e: Event) {
        if (this.readyState === this.OPEN) {
            this.sendMsg({ token: uni.getStorageSync("userInfo").token })
        }
        console.log("已连接", e);
    }
    handleClose(e: Event) {
        if (this.heartbeatTimer) {
            clearInterval(this.heartbeatTimer);
            this.heartbeatTimer = null;
        }
        if (this.reconnectingTimer) {
            clearTimeout(this.reconnectingTimer);
            this.reconnectingTimer = null;
        }
 this.reconnect();
    }
    handleError(e: Event) {
        this.reconnect();
        uni.showToast({ title: "连接错误" })
        console.log("连接错误", e);
    }


    reconnect() {
        // 异步方法使用promise接收值
        this.reconnectingTimer = setTimeout(() => {
            this.wsReconnect();
        }, 500);
    }
    receiveMsg({ data }: any) {
        return JSON.parse(data);
    }
    sendMsg(data: any) {
        if (this.readyState === this.OPEN) {
            this.send(JSON.stringify(data));
        } else {
            uni.showToast({ title: "连接已关闭，消息推送失败" });
        }
    }
    forceClose() {
        if (this.readyState === this.OPEN) {
            socketStore.socketIsOpen = false;
            this.close();
        } else {
            setTimeout(() => {
                this.forceClose();
            }, 1000);
        }
    }

    waitForResponese() {
        setTimeout(() => {
            try {
                this.close();
            } catch (error) {
                console.log("断开连接时执行close会捕获到错误", error);
            }
        }, 2000);
    }
    static create(url: string, wsReconnect: Function) {
        return new Ws(url, wsReconnect);
    }
}
